import time
import math
import json
from django.shortcuts import render, render_to_response
from django.http import HttpResponse
from django.core import serializers
from microerp.apps.base.models import *
from microerp.apps.base.views import *
from microerp.apps.product.models import Product
from microerp.apps.product.forms import ProductForm

'''
新建产品 包含GET和POST请求
'''
def new_product(request):
	if islogin(request):
		#POST请求，添加产品
		if request.method=='POST':
			form=ProductForm(request.POST)
			#如果表单有效 开始添加产品
			if form.is_valid():
				user=Users.objects.filter(id=get_user_id(request))[0]
				product=Product()
				product.user=user
				product=form_to_model(form, product)
				product.add_date=time.strftime("%Y-%m-%d", time.localtime())
				product.code=str(set_code(user))
				product.save()
				return render(request, 'product/new-product.html',{'sign':True,'form':form})
			else:
				print(form)
				return render(request, 'product/new-product.html',{'sign':False,'form':form,'error':True})	
		#Get请求，直接返回该页面
		else:
			return render(request, 'product/new-product.html')
	else:
		return render(request, 'base/signin.html')



'''
浏览产品列表 只有GET方法 通过url中的参数来查询
'''
def product_list(request):
	if islogin(request):
		user=Users.objects.filter(id=get_user_id(request))[0]
		#query-----查询关键字
		#page------页码（每页10条数据）
		query = request.GET.get('query')
		page = request.GET.get('page',1)
		#得到顾客列表数据
		prod_list,totalRecords=get_products(query,user,int(page))
		#开始获得分页数据
		totalPage=math.ceil(totalRecords/10)
		return render(request, 'product/product-list.html',{'list':prod_list,'query':query,"totalPage":totalPage,"totalRecords":totalRecords})
	else:
		return render(request, 'base/signin.html')

'''
Form和Model的数据对换，将Form中的值赋给MODEL
'''
def form_to_model(form,model):
	model.name=form.cleaned_data["name"]
	model.kind=form.cleaned_data["kind"]
	model.img=form.cleaned_data["img"]
	model.state=form.cleaned_data["state"]
	model.inventory=form.cleaned_data["inventory"]
	model.img=form.cleaned_data["img"]
	model.cost=form.cleaned_data["cost"]
	model.price=form.cleaned_data["price"]
	model.producer=form.cleaned_data["producer"]
	model.notes=form.cleaned_data["notes"]
	return model

'''
新建产品时设置产品编号
'''
def set_code(user):
	lists=Product.objects.filter(user=user).order_by("-id")
	if lists.count() is 0:
		return 1
	else:
		return int(lists[0].code)+1


'''
获得产品列表
obj:查询关键字
user:当前用户
page:当前页数
'''
def get_products(obj,user,page):
	prod_list=[]
	totalRecords=0;
	if obj:
		products=Product.objects.filter(user=user).filter(name__icontains=str(obj)).order_by("-id")
		prod_list=products[(page-1)*10:page*10-1]
		totalRecords=products.count()
	else:
		products=Product.objects.filter(user=user).order_by("-id")
		prod_list=products[(page-1)*10:page*10-1]
		totalRecords=products.count()
	return prod_list,totalRecords


#API

'''
根据商品代码获取商品的详细信息
@code=商品代码
'''
def api_get_prod(request):
	if islogin(request):
		user=Users.objects.filter(id=get_user_id(request))[0]
		code=request.GET.get('code')
		product=Product()
		if code:
			product=Product.objects.filter(user=user).filter(code=code)
		return HttpResponse(serializers.serialize('json',product))	
		#return HttpResponse(json.dumps(product.as_json()), content_type="application/json")
	else:
		return HttpResponse()

def api_get_prods(request):
	if islogin(request):
		user=Users.objects.filter(id=get_user_id(request))[0]
		result_set=Product.objects.filter(user=user).filter(state=1)
		results=[ob.as_json() for ob in result_set]
		return HttpResponse(json.dumps(results), content_type="application/json")
	else:
		return render(request, 'base/signin.html')